
#include <unistd.h>  
#include <net/if.h>  
#include <sys/ioctl.h>  
#include <sys/types.h>  
#include <sys/socket.h>  
#include <stdio.h>
#include <string.h> 
#include "hwinfo.h"
  
int get_mac_address_by_ioctl(char* mac_address)  
{  
    int sock = socket(AF_INET, SOCK_STREAM, 0);  
    if (sock < 0)  
    {  
        return(0);  
    }  
  
    struct ifreq ifr = { 0 };  
    strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name) - 1);  
    int ret = (ioctl(sock, SIOCGIFHWADDR, &ifr) >= 0);  
  
    close(sock);  
  
    const char hex[] =   
    {  
        '0', '1', '2', '3', '4', '5', '6', '7',   
        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'   
    };  
    for (int index = 0; index < 6; ++index)  
    {  
         size_t value = ifr.ifr_hwaddr.sa_data[index] & 0xFF;  
         mac_address[2 * index + 0] = hex[value / 16];  
         mac_address[2 * index + 1] = hex[value % 16];  
    }  
  
    return(ret);  
}  
#ifdef USE_DMIDECODE
static void parse_mac_address(const char * file_name, const char * match_words, std::string & mac_address)  
{  
    mac_address.c_str();  
  
    std::ifstream ifs(file_name, std::ios::binary);  
    if (!ifs.is_open())  
    {  
        return;  
    }  
  
    char line[4096] = { 0 };  
    while (!ifs.eof())  
    {  
        ifs.getline(line, sizeof(line));  
        if (!ifs.good())  
        {  
            break;  
        }  
  
        const char * mac = strstr(line, match_words);  
        if (NULL == mac)  
        {  
            continue;  
        }  
        mac += strlen(match_words);  
  
        while ('\0' != mac[0])  
        {  
            if (' ' != mac[0] && ':' != mac[0])  
            {  
                mac_address.push_back(mac[0]);  
            }  
            ++mac;  
        }  
  
        if (!mac_address.empty())  
        {  
            break;  
        }  
    }  
  
    ifs.close();  
}  
  
static int get_mac_address_by_system(std::string & mac_address)  
{  
    mac_address.c_str();  
  
    const char * lshw_result = ".lshw_result.txt";  
    char command[512] = { 0 };  
    snprintf(command, sizeof(command), "lshw -c network | grep serial | head -n 1 > %s", lshw_result);  
  
    if (0 == system(command))  
    {  
        parse_mac_address(lshw_result, "serial:", mac_address);  
    }  
  
    unlink(lshw_result);  
  
    return(!mac_address.empty());  
}  
#endif
int get_mac_address(char* mac_address)  
{  
    if (get_mac_address_by_ioctl(mac_address))  
    {  
        return(1);  
    }  
	#ifdef USE_DMIDECODE
    if (get_mac_address_by_system(mac_address))  
    {  
        return(1);  
    }  
	#endif
    return(0);  
}  